package com.wwj.depository.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wwj.common.constant.CommonCodeEnum;
import com.wwj.common.constant.CommonConstant;
import com.wwj.common.entitiy.R;
import com.wwj.depository.constant.ConstantFinal;
import com.wwj.depository.entity.DepositoryExpressInformationEntity;
import com.wwj.depository.entity.DepositoryLocationEntity;
import com.wwj.depository.entity.UserEntity;
import com.wwj.depository.exception.OpenFeignException;
import com.wwj.depository.feign.UserFeignService;
import com.wwj.depository.service.DepositoryLocationService;
import com.wwj.depository.service.ExpressService;
import com.wwj.depository.vo.DataStatisticsVo;
import com.wwj.depository.vo.ExpressVo;
import com.wwj.depository.vo.UpdateVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.geom.QuadCurve2D;
import java.util.ArrayList;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("/depository")
public class ExpressController {

    @Resource
    private ExpressService expressService;

    @Resource
    private DepositoryLocationService depositoryLocationService;

    @Resource
    private UserFeignService userFeignService;

    /**
     * 数据可视化服务
     * http://127.0.0.1:88/api/depository/dataStatistics
     */
    @GetMapping("/dataStatistics")
    public R<Object> getDataStatistics(HttpServletRequest request) {
        // 查询多项数据
        DataStatisticsVo dataStatisticsVo = expressService.selectManyData();
        return R.ok(CommonCodeEnum.SUCCESS.getCode(), "获取可视化数据成功", dataStatisticsVo);
    }

    /**
     * 获取快递信息的表格数据(分页)
     * http://127.0.0.1:88/api/depository/getExpressData/currentPage/totalPage?query="xxx"
     */
    @GetMapping("/getExpressData/{currentPage}/{pageSize}")
    public R<Object> getExpressData(@PathVariable("currentPage") String currentPage,
                                    @PathVariable("pageSize") String pageSize,
                                    @RequestParam(value = "query", required = false) String query,
                                    HttpServletRequest request) {
        if (query == null) query = "";  // 防止空指针错误
        // token没有过期
        PageInfo<ExpressVo> pageInfo = expressService.selectExpressData(currentPage, pageSize, query);
        return R.ok(CommonCodeEnum.SUCCESS.getCode(), CommonCodeEnum.SUCCESS.getMsg(), pageInfo);
    }

    /**
     * 根据快递信息id删除信息，根据库存id字段修改仓库表信息为未签收状态
     * http://127.0.0.1:88/api/depository/removeExpressData?informationId=1&locationId=4&userId=2110106
     * todo 后期非空判断以及其余功能 JSR303
     */
    @DeleteMapping("/removeExpressData")
    public R<Object> removeExpressData(@RequestParam(value = "informationId") String informationId,
                                       @RequestParam(value = "locationId") String locationId) {
        expressService.removeById(informationId);
        DepositoryLocationEntity depositoryLocationEntity = depositoryLocationService.getById(locationId);
        depositoryLocationEntity.setLocationStorage(ConstantFinal.VALUE_LOCATION_NO_STORAGE);  // 仓位空状态
        depositoryLocationService.updateById(depositoryLocationEntity);
        return R.ok("删除成功");
    }

    /**
     * 获取快递的详细信息
     * http://127.0.0.1:88/api/depository/getExpressDescriptionData?informationId=4&locationId=7
     */
    @GetMapping("/getExpressDescriptionData")
    public R<Object> getExpressDescriptionData(@RequestParam(value = "informationId") String informationId,
                                               @RequestParam(value = "locationId") String locationId) {
        // 根据informationId查询数据
        DepositoryExpressInformationEntity expressInformationEntity = expressService.getById(informationId);
        // 根据locationId查询数据
        DepositoryLocationEntity depositoryLocationEntity = depositoryLocationService.getById(locationId);
        ExpressVo expressVo = new ExpressVo();
        BeanUtils.copyProperties(expressInformationEntity, expressVo);
        BeanUtils.copyProperties(depositoryLocationEntity, expressVo);
        return R.ok(CommonCodeEnum.SUCCESS.getCode(), CommonCodeEnum.SUCCESS.getMsg(), expressVo);
    }

    /**
     * 更新表单信息
     * http://127.0.0.1:88/api/depository/update
     */
    @PutMapping("/update")
    public R<Object> updateForm(@RequestBody(required = false) UpdateVo updateVo) {
        // 查询是否存在当前工号没有就返回
        int code = -1;
        try {
            code = userFeignService.selectUserExist(updateVo.getUserId()).getCode();
        } catch (OpenFeignException e) {
            e.printStackTrace();
        }
        if (code == CommonCodeEnum.SUCCESS.getCode()) {
            // 用户存在执行更新业务
            // 查询该informationId的更新之前信息
            DepositoryExpressInformationEntity willUpdateExpress = expressService.getById(updateVo.getInformationId());
            // 判断是否有签收时间 前端禁用了有签收时间的更新操作 --》 但凡是更新了时间就一定是签收了快递就需要对库位表数据解除站占用
            if (updateVo.getInformationSignTime() != null) {
                // 快递签收操作
                // 修改库位表占用情况
                DepositoryLocationEntity oldDepository = depositoryLocationService.getById(willUpdateExpress.getLocationId());  // 获取该快递所在库存详细信息
                oldDepository.setLocationStorage(ConstantFinal.VALUE_LOCATION_NO_STORAGE);  // 设置之前的存储数据为没有存储状态
                depositoryLocationService.updateById(oldDepository);  // 更新之前的库存数据为非存储状态
            }else {
                // 换库存操作 1、查询快递表locationId 2、更新库位表该locationId为不占用状态 3、获取新的locationId判断是不占用的情况下更新为占用状态
                depositoryLocationService.updateById(new DepositoryLocationEntity(willUpdateExpress.getLocationId(),
                        null, ConstantFinal.VALUE_LOCATION_NO_STORAGE));
                DepositoryLocationEntity newLocationEntity = depositoryLocationService.getById(updateVo.getLocationId());
                if (ConstantFinal.VALUE_LOCATION_NO_STORAGE.equals(newLocationEntity.getLocationStorage())) {
                    // 更新为占用状态
                    depositoryLocationService.updateById(new DepositoryLocationEntity(updateVo.getLocationId(),
                            null, ConstantFinal.VALUE_LOCATION_IS_STORAGE));
                }else {
                    return R.error(CommonCodeEnum.ERROR.getMsg());
                }
            }
            // 更新快递信息表数据
            // 放入修改的数据
            willUpdateExpress.setInformationCreateTime(updateVo.getInformationCreateTime());
            willUpdateExpress.setInformationSignTime(updateVo.getInformationSignTime());
            willUpdateExpress.setInformationNumber(updateVo.getInformationNumber());
            willUpdateExpress.setLocationId(updateVo.getLocationId());
            willUpdateExpress.setUserId(updateVo.getUserId());
            // 更新快递信息数据
            expressService.updateById(willUpdateExpress);
            return R.ok("更新成功");
        } else {
            // 用户不存在
            return R.error(CommonCodeEnum.USER_NO_EXIST.getCode(), CommonCodeEnum.UPDATE_DATA.getMsg());
        }
    }

    /**
     * 快递信息新增操作
     * http://127.0.0.1:88/api/depository/add
     */
    @PostMapping("/add")
    public R<Object> add(@RequestBody UpdateVo addVo) {
        // 判断学/工是否存在
        int code = -1;
        try {
            code = userFeignService.selectUserExist(addVo.getUserId()).getCode();
        } catch (OpenFeignException e) {
            e.printStackTrace();
        }
        if (code == CommonCodeEnum.SUCCESS.getCode()) {
            //  用户存在处理业务
            if (addVo.getInformationSignTime() == null) {
                // 快递没有签收的新增
                // 更新仓位仓储信息数据
                DepositoryLocationEntity oldLocation = depositoryLocationService.getById(addVo.getLocationId());
                oldLocation.setLocationStorage(ConstantFinal.VALUE_LOCATION_IS_STORAGE);  // 设置占用
                depositoryLocationService.updateById(oldLocation); // 更新仓储信息
            }
            // 有签收时间不用更新仓储信息直接新增
            // 查询用户的所有信息
            R<UserEntity> userR;
            try {
                userR = userFeignService.getUserById(addVo.getUserId());
            } catch (OpenFeignException e) {
                e.printStackTrace();
                return R.error(CommonCodeEnum.ERROR.getCode(), CommonCodeEnum.ERROR.getMsg());
            }
            if (userR.getCode() == CommonCodeEnum.SUCCESS.getCode()) {
                // 成功获取
                UserEntity userEntity = userR.getData();
                // 新增快递信息数据
                expressService.save(new DepositoryExpressInformationEntity(null,
                        userEntity.getUserName(),
                        userEntity.getUserMobile(),
                        addVo.getInformationNumber(),
                        addVo.getInformationCreateTime(),
                        addVo.getInformationSignTime(),
                        addVo.getLocationId(),
                        userEntity.getUserId()));
                return R.ok("新增成功");
            } else {
                return R.error("获取失败");
            }
        } else {
            // 不存在返回
            return R.error(CommonCodeEnum.USER_NO_EXIST.getCode(), CommonCodeEnum.USER_NO_EXIST.getMsg());
        }
    }

    /**
     * 批量删除快递信息
     * http://127.0.0.1:88/api/depository/batchDelete
     */
    @DeleteMapping("/batchDelete")
    public R<Object> batchDelete(@RequestBody List<UpdateVo> batchDeleteList){
        List<String> informationIds = new ArrayList<>();
        batchDeleteList.forEach(item -> {
            // 抽取快递信息表id
            informationIds.add(item.getInformationId());
            if (item.getInformationSignTime() == null) {
                // 没有签收日期表示需要将仓库所对应的数据更新为未存储
                depositoryLocationService.updateById(new DepositoryLocationEntity(
                        item.getLocationId(),
                        null,
                        ConstantFinal.VALUE_LOCATION_NO_STORAGE
                ));
            }
        });
        // 批量删除快递信息表数据
        boolean flag = expressService.removeByIds(informationIds);
        if (!flag) {
            return R.error("批量删除失败");
        }
        return R.ok("批量删除成功");
    }

    /**
     * 传参 ids，判断是否可以删除该用户接口，查表操作
     * OpenFeign
     */
    @GetMapping("/userIdExist")
    public R<Object> userIdExist(@RequestParam("ids") List<String> ids){
        for (String userId : ids) {
            QueryWrapper<DepositoryExpressInformationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(ConstantFinal.FIELD_USER_ID, userId);
            List<DepositoryExpressInformationEntity> list = expressService.list(queryWrapper);
            if (list.size() != 0){
                return R.error(CommonCodeEnum.USER_EXIST.getCode(), CommonCodeEnum.USER_EXIST.getMsg());
            }
        }
        return R.ok("可以删除用户");
    }

}
